/*
 * @Descripttion:
 * @version:
 * @Author: gengzhi
 * @Date: 2020-08-18 10:28:24
 * @LastEditors: gengzhi
 * @LastEditTime: 2020-08-18 10:34:41
 */
package ddd_infrastructure

import (
	"context"
	"kendoDDD/ddd_interfaces"
	"kendoDDD/dddcore"
)

type eventSourcedRepository struct {
	streamName string
	eventStore dddcore.EventStore
	eventBus   dddcore.EventBus
}

func (r *eventSourcedRepository) Save(ctx context.Context, u dddcore.IEventMsg) error {
	err := r.eventStore.Store(u.Changes())
	if err != nil {
		return err
	}
	for _, event := range u.Changes() {
		r.eventBus.Publish(ctx, event.Metadata.Type, *event)
	}
	return nil
}

func NewESRepository(streamName string, store dddcore.EventStore, bus dddcore.EventBus) ddd_interfaces.IESRepository {
	return &eventSourcedRepository{streamName, store, bus}
}
